package exteditapp.state;

import exteditapp.AppletIterator;
import exteditapp.FileDefault;
import exteditapp.action.ActionIdling;
import exteditapp.command.CommandCheck;

/**
 * State - none (no file is loaded)
 * @author Arturas Smorgun, arturas@smorgun.lt
 */
public class StateIdling extends IState {

	protected int checkPeriod = 0;
	
	protected int lastExec = 0;
	
	/**
	 * Default constructor
	 * @param iterator is system iterator, which performs all actions
	 * @param file this is file, which state we will hold
	 */
	public StateIdling(AppletIterator iterator, FileDefault file) {
		super(iterator, file);
		start();
	}
	public StateIdling(AppletIterator iterator, FileDefault file, boolean doRegister){
		super(iterator, file, doRegister);
		start();
	}
	
	protected void start() {
		this.setAction(new ActionIdling());
		label = "EDIT IN EXTERNAL EDITOR";
		progress = 0;
		while(checkPeriod <= 0){
			checkPeriod = Integer.parseInt(file.getModule().getSettings().getParameter("fileCheckInterval"));
			if(checkPeriod > 0)
				break;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * Handling of new state
	 */
	public boolean handle() {
		//
		if(this.getLifetime() > 0 && this.getLifetime() % checkPeriod == 0 && lastExec != this.getLifetime()){
			file.getModule().getInvoker().execute(new CommandCheck(this.file));
			lastExec = this.getLifetime();
		}
		return false;
	}
	
}
